<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LangChain4j AI助手</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg-primary: #f0f2f5;
            --bg-secondary: #ffffff;
            --text-primary: #050505;
            --text-secondary: #65676b;
            --user-msg-bg: #0084ff;
            --user-msg-text: #ffffff;
            --ai-msg-bg: #f0f0f0;
            --ai-msg-text: #050505;
            --input-bg: #ffffff;
            --input-border: #e4e6eb;
            --shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
            --accent-color: #6a11cb;
        }

        .dark-mode {
            --bg-primary: #18191a;
            --bg-secondary: #242526;
            --text-primary: #e4e6eb;
            --text-secondary: #b0b3b8;
            --user-msg-bg: #0084ff;
            --user-msg-text: #ffffff;
            --ai-msg-bg: #3a3b3c;
            --ai-msg-text: #e4e6eb;
            --input-bg: #3a3b3c;
            --input-border: #3a3b3c;
            --shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
            --accent-color: #8e44ad;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: var(--bg-primary);
            color: var(--text-primary);
            transition: var(--transition);
            height: 100vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        header {
            background-color: var(--bg-secondary);
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: var(--shadow);
            z-index: 10;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .logo-icon {
            background: linear-gradient(135deg, var(--accent-color) 0%, #2575fc 100%);
            color: white;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
        }

        .logo-text {
            font-size: 1.4rem;
            font-weight: 600;
        }

        .header-controls {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .theme-toggle, .new-chat-btn {
            background: none;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 8px 14px;
            border-radius: 20px;
            font-size: 0.9rem;
            background-color: rgba(0, 0, 0, 0.05);
        }

        .dark-mode .theme-toggle, .dark-mode .new-chat-btn {
            background-color: rgba(255, 255, 255, 0.05);
        }

        .theme-toggle:hover, .new-chat-btn:hover {
            background-color: rgba(0, 0, 0, 0.1);
            color: var(--text-primary);
        }

        .dark-mode .theme-toggle:hover, .dark-mode .new-chat-btn:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 20px;
            position: relative;
        }

        .welcome-section {
            text-align: center;
            max-width: 700px;
            margin: 0 auto;
            padding: 30px 0;
        }

        .welcome-title {
            font-size: 2.2rem;
            margin-bottom: 15px;
            background: linear-gradient(135deg, var(--accent-color) 0%, #2575fc 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .welcome-subtitle {
            color: var(--text-secondary);
            font-size: 1.1rem;
            margin-bottom: 30px;
            line-height: 1.6;
        }

        .message {
            max-width: 85%;
            padding: 12px 16px;
            border-radius: 18px;
            margin-bottom: 8px;
            position: relative;
            animation: fadeIn 0.3s ease;
            word-wrap: break-word;
            line-height: 1.5;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .user-message {
            background-color: var(--user-msg-bg);
            color: var(--user-msg-text);
            align-self: flex-end;
            border-bottom-right-radius: 4px;
        }

        .ai-message {
            background-color: var(--ai-msg-bg);
            color: var(--ai-msg-text);
            align-self: flex-start;
            border-bottom-left-radius: 4px;
        }

        .ai-typing {
            display: flex;
            align-items: center;
            gap: 8px;
            color: var(--text-secondary);
            padding: 15px 20px;
            align-self: flex-start;
        }

        .typing-animation {
            display: flex;
            gap: 4px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background-color: var(--text-secondary);
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: 0s; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-5px); }
        }

        .message-time {
            font-size: 0.7rem;
            color: var(--text-secondary);
            margin-top: 4px;
            text-align: right;
        }

        .input-container {
            background-color: var(--bg-secondary);
            padding: 15px 20px;
            display: flex;
            gap: 12px;
            box-shadow: var(--shadow);
            z-index: 10;
        }

        .input-box {
            flex: 1;
            display: flex;
            background-color: var(--input-bg);
            border-radius: 24px;
            border: 1px solid var(--input-border);
            padding: 0 15px;
            transition: var(--transition);
        }

        .input-box:focus-within {
            border-color: #0084ff;
            box-shadow: 0 0 0 2px rgba(0, 132, 255, 0.2);
        }

        .input-box input {
            flex: 1;
            background: none;
            border: none;
            padding: 12px 0;
            color: var(--text-primary);
            font-size: 1rem;
            outline: none;
        }

        .send-button {
            background: linear-gradient(135deg, var(--accent-color) 0%, #2575fc 100%);
            color: white;
            border: none;
            border-radius: 50%;
            width: 42px;
            height: 42px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 1.2rem;
            transition: var(--transition);
        }

        .send-button:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 12px rgba(106, 17, 203, 0.3);
        }

        .send-button:disabled {
            background: var(--text-secondary);
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .session-id {
            font-size: 0.8rem;
            color: var(--text-secondary);
            text-align: center;
            padding: 5px 0;
        }

        @media (max-width: 768px) {
            .message {
                max-width: 90%;
            }

            .welcome-title {
                font-size: 1.8rem;
            }

            .header-controls {
                gap: 8px;
            }

            .theme-toggle span, .new-chat-btn span {
                display: none;
            }
        }
    </style>
</head>
<body>
<header>
    <div class="logo">
        <div class="logo-icon">
            <i class="fas fa-brain"></i>
        </div>
        <div class="logo-text">LangChain4j AI</div>
    </div>
    <div class="header-controls">
        <button class="new-chat-btn" id="newChatBtn">
            <i class="fas fa-plus"></i>
            <span>新建会话</span>
        </button>
        <button class="theme-toggle" id="themeToggle">
            <i class="fas fa-moon"></i>
            <span>夜间模式</span>
        </button>
    </div>
</header>

<div class="chat-container" id="chatContainer">
    <div class="welcome-section">
        <h1 class="welcome-title">LangChain4j AI助手</h1>
        <p class="welcome-subtitle">基于Spring Boot和LangChain4j技术构建的智能对话系统。输入您的问题，获取专业解答，支持多轮对话上下文理解。</p>
    </div>
</div>

<div class="session-id" id="sessionInfo">
    会话ID: <span id="sessionId">未创建</span>
</div>

<div class="input-container">
    <div class="input-box">
        <input type="text" id="userInput" placeholder="输入您的问题..." autocomplete="off">
    </div>
    <button class="send-button" id="sendButton">
        <i class="fas fa-paper-plane"></i>
    </button>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const chatContainer = document.getElementById('chatContainer');
        const userInput = document.getElementById('userInput');
        const sendButton = document.getElementById('sendButton');
        const themeToggle = document.getElementById('themeToggle');
        const newChatBtn = document.getElementById('newChatBtn');
        const sessionIdDisplay = document.getElementById('sessionId');

        // 会话状态
        let currentSessionId = null;
        let isWaitingForResponse = false;

        // 初始化
        createNewSession();

        // 新建会话
        newChatBtn.addEventListener('click', createNewSession);

        // 发送消息
        sendButton.addEventListener('click', sendMessage);
        userInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 主题切换
        themeToggle.addEventListener('click', function() {
            document.body.classList.toggle('dark-mode');
            const icon = themeToggle.querySelector('i');
            if (document.body.classList.contains('dark-mode')) {
                icon.classList.replace('fa-moon', 'fa-sun');
                themeToggle.querySelector('span').textContent = '日间模式';
            } else {
                icon.classList.replace('fa-sun', 'fa-moon');
                themeToggle.querySelector('span').textContent = '夜间模式';
            }
        });

        // 创建新会话
        function createNewSession() {
            // 清除聊天内容
            chatContainer.innerHTML = `
                    <div class="welcome-section">
                        <h1 class="welcome-title">LangChain4j AI助手</h1>
                        <p class="welcome-subtitle">基于Spring Boot和LangChain4j技术构建的智能对话系统。输入您的问题，获取专业解答，支持多轮对话上下文理解。</p>
                    </div>
                `;

            // 生成新的会话ID（使用时间戳）
            currentSessionId = Date.now().toString();
            sessionIdDisplay.textContent = currentSessionId;

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 发送消息到后端
        function sendMessage() {
            const message = userInput.value.trim();
            if (!message || isWaitingForResponse) return;

            // 添加用户消息到界面
            addMessageToChat(message, 'user');
            userInput.value = '';

            // 显示AI正在输入
            showTypingIndicator();

            // 发送请求到后端
            isWaitingForResponse = true;
            sendButton.disabled = true;

            // 使用fetch API发送请求
            fetch(`/chat?memoryId=${currentSessionId}&message=${encodeURIComponent(message)}`)
                .then(response => {
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder('utf-8');
                    let aiResponse = '';

                    // 处理流式响应
                    function readStream() {
                        return reader.read().then(({ value, done }) => {
                            if (done) {
                                hideTypingIndicator();
                                isWaitingForResponse = false;
                                sendButton.disabled = false;
                                return;
                            }

                            // 解码并添加新内容
                            const chunk = decoder.decode(value, { stream: true });
                            aiResponse += chunk;

                            // 更新AI消息
                            updateAIMessage(aiResponse);

                            // 继续读取
                            return readStream();
                        });
                    }

                    return readStream();
                })
                .catch(error => {
                    console.error('请求出错:', error);
                    addMessageToChat('抱歉，请求处理过程中出现错误。', 'ai');
                    hideTypingIndicator();
                    isWaitingForResponse = false;
                    sendButton.disabled = false;
                });
        }

        // 添加消息到聊天界面
        function addMessageToChat(message, sender) {
            hideTypingIndicator();

            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;

            // 添加消息内容
            messageDiv.innerHTML = `
                    <div class="message-content">${formatMessage(message)}</div>
                    <div class="message-time">${getCurrentTime()}</div>
                `;

            chatContainer.appendChild(messageDiv);

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 更新AI消息（流式响应）
        function updateAIMessage(message) {
            let aiMessage = document.querySelector('.ai-message:last-child');

            // 如果没有AI消息，创建一个新的
            if (!aiMessage) {
                hideTypingIndicator();
                aiMessage = document.createElement('div');
                aiMessage.className = 'message ai-message';
                aiMessage.innerHTML = `
                        <div class="message-content">${formatMessage(message)}</div>
                        <div class="message-time">${getCurrentTime()}</div>
                    `;
                chatContainer.appendChild(aiMessage);
            } else {
                // 更新现有消息
                aiMessage.querySelector('.message-content').innerHTML = formatMessage(message);
            }

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 显示输入指示器
        function showTypingIndicator() {
            hideTypingIndicator();

            const typingDiv = document.createElement('div');
            typingDiv.className = 'ai-typing';
            typingDiv.innerHTML = `
                    <span>AI正在思考</span>
                    <div class="typing-animation">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                `;

            chatContainer.appendChild(typingDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 隐藏输入指示器
        function hideTypingIndicator() {
            const typingIndicator = document.querySelector('.ai-typing');
            if (typingIndicator) {
                typingIndicator.remove();
            }
        }

        // 格式化消息（简单Markdown支持）
        function formatMessage(message) {
            // 转换换行符
            message = message.replace(/\n/g, '<br>');

            // 简单加粗处理
            message = message.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

            return message;
        }

        // 获取当前时间
        function getCurrentTime() {
            const now = new Date();
            return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
        }
    });
</script>
</body>
</html>